from rest_framework.viewsets import ModelViewSet
from aaa import models
from rest_framework import serializers
from rest_framework.response import Response
import json
from django.http import JsonResponse
from aaa.utils.pager import myPageNumberPagination

class goodsSerializer(serializers.ModelSerializer):
    goods_cat = serializers.SerializerMethodField()
    goods_cat_name = serializers.SerializerMethodField()
    goods_impact = serializers.CharField(source='get_goods_impact_display')
    class Meta:
        model = models.Goods
        fields = ['goods_id','goods_cat','goods_cat_name','goods_state','goods_impact','goods_name','goods_sn',
                  'responsible_person','deal','solve_date','pics','add_time','upd_time','attrs','goods_introduce']

    def get_goods_cat(self,row):
        print('get_goods_cat row',row.goods_cat)
        cate = json.loads(row.goods_cat)
        if isinstance(cate,list):
            cate = cate[2]
        obj = models.Categories.objects.get(cat_id=cate)
        cat_id,cat_pid,self.cat_name = obj.cat_id,obj.cat_pid,obj.cat_name
        second_obj = models.Categories.objects.get(cat_id=cat_pid)
        second_pid,first_pid,self.second_cat_name = second_obj.cat_id,second_obj.cat_pid,second_obj.cat_name
        print(self.cat_name,self.second_cat_name)
        if second_pid:
            first_obj = models.Categories.objects.get(cat_id=first_pid)
            self.first_cat_name = first_obj.cat_name
            cat_id_list = []
            cat_id_list.append(first_pid)
            cat_id_list.append(second_pid)
            cat_id_list.append(cat_id)
            return cat_id_list

    def get_goods_cat_name(self,row):
        # print('get_goods_cat_name row',row.goods_cat)
        # obj = models.Categories.objects.get(cat_id=int(row.goods_cat))
        # cat_pid,cat_name = obj.cat_pid,obj.cat_name
        # second_obj = models.Categories.objects.get(cat_id=cat_pid).cat_name
        # second_pid,second_cat_name = second_obj.cat_id,second_obj.cat_name
        # print(cat_name,second_cat_name)
        # if second_pid:
        #     first_pid = models.Categories.objects.get(cat_id=second_pid).cat_pid
        # cat_name_list = []
        # cat_name_list.append(self.second_cat_name)
        # cat_name_list.append(self.cat_name)
        # cat_name_list.append(cat_id)
        return self.second_cat_name,self.first_cat_name+' - '+self.cat_name

class goodsInfoView(ModelViewSet):
    queryset = models.Goods.objects.all()
    serializer_class = goodsSerializer
    # pagination_class = PageNumberPagination
    authentication_classes = []

    def list(self, request, *args, **kwargs):
        pg = myPageNumberPagination()
        xx = pg.paginate_queryset(queryset=self.queryset,request=request,view=self)
        ser = goodsSerializer(instance=xx,many=True)
        ret = {}
        ret['data'] = json.dumps(ser.data)
        ret['total'] = self.queryset.count()
        return JsonResponse(ret)

    def create(self, request, *args, **kwargs):
        print('addGoods res',request.data)
        data = request.data
        # if not data.get('goods_state'):
        #     temp_goods_state = True
        try:
            obj = models.Goods.objects.create(goods_name=data['goods_name'],goods_sn=data['goods_sn'],goods_state=True,
                    goods_impact=data['goods_impact'],responsible_person=data['responsible_person'],deal=data['deal'],solve_date=data['solve_date'],
                    goods_cat=data['goods_cat'],pics=data['pics'],goods_introduce=data['goods_introduce'],attrs=data['attrs'])
            return JsonResponse({'meta': {'status': 201, 'msg': 'ok'}})
        except Exception as e:
            print('e',e)

    def update(self, request, *args, **kwargs):
        print('updateGoods res', request.data)
        data = request.data
        state = data['goods_impact']
        solve_date = data['solve_date']
        print('solve_date type',type(solve_date),solve_date)
        if state == '1' or state == '高':
            state = 1
        elif state == '2' or state == '中':
            state = 2
        else:
            state = 3
        print('state111', state)
        try:
            obj = models.Goods.objects.filter(goods_id=data['goods_id']).update(
                goods_name=data['goods_name'], goods_sn=data['goods_sn'], goods_state=data['goods_state'],
                goods_impact=state, responsible_person=data['responsible_person'], deal=data['deal'],
                solve_date=solve_date,goods_cat=data['goods_cat'], pics=data['pics'], goods_introduce=data['goods_introduce'],
                attrs=data['attrs'])
            return JsonResponse({'meta': {'status': 201, 'msg': 'ok'}})
        except Exception as e:
            print('e',e)
